//
//  XXTextView.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/28.
//

import UIKit
import SnapKit

class XXTextView: XXView,UITextViewDelegate {

    var placeholder:String{
        set{
            self.lblPlaceholder.text = newValue
        }
        get{
            return self.lblPlaceholder.text ?? ""
        }
    }
    var font:UIFont{
        set{
            self.txtView.font = newValue
        }
        get{
            return self.txtView.font ?? UIFont.system(15)
        }
    }
    var textColor:UIColor{
        set{
            self.txtView.textColor = newValue
        }
        get{
            return self.txtView.textColor ?? UIColor.black
        }
    }
    var text:String{
        set{
            self.txtView.text = newValue
        }
        get{
            return self.txtView.text ?? ""
        }
    }
    
    private lazy var txtView : UITextView = {
        let view = UITextView.init()
        view.font = .system(15)
        view.delegate = self
        return view
    } ()
    
    private lazy var lblPlaceholder : XXLabel = {
        let label = XXLabel.init(font: .system(15), color: .x999)
        return label
    } ()
    
    var maxLength : Int = 200 // 最大输入长度
    override func setupUI() {
        self.addSubview(txtView)
        txtView.snp.makeConstraints { (make) in
            make.top.left.equalTo(10)
            make.bottom.right.equalTo(-10)
        }
        self.addSubview(lblPlaceholder)
        lblPlaceholder.snp.makeConstraints { (make) in
            make.top.left.equalTo(10)
        }
    }
    
    // MARK: - UITextViewDelegate
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "" {
            return true
        }
        let str:String = textView.text ?? ""
        let count:Int = str.count + text.count
        if count <= maxLength {
            return true
        }else{
            return false
        }
    }
    func textViewDidBeginEditing(_ textView: UITextView) {
        lblPlaceholder.isHidden = true
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            lblPlaceholder.isHidden = false
        }
    }

}
